<!--
 * @Author: ZAL 2177624751@qq.com
 * @Date: 2024-12-23 14:12:47
 * @LastEditors: ZAL 2177624751@qq.com
 * @LastEditTime: 2025-03-31 21:40:59
 * @FilePath: \shop_app_vue3\pages\user\user.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <view class="user-container">
    <!-- 顶部个人信息卡片 -->
    <view class="profile-section">
      <!-- 右上角设置按钮 -->
      <view class="header-actions">
        <view class="action-btn" @click="handleSettings">
          <u-icon name="setting" size="28" color="#fff"></u-icon>
        </view>
      </view>

      <view class="profile-header">
        <view class="avatar-wrapper">
          <u-avatar
            :src="userInfo?.avatarUrl || '/static/images/default-avatar.png'"
            size="120"
            shape="circle"
          >
            <template #error>
              <view class="avatar-placeholder">
                {{ userInfo?.nickname?.[0] || '游' }}
              </view>
            </template>
          </u-avatar>
          <view class="vip-badge" v-if="userInfo?.is_vip === 1">
            <u-icon name="level" size="12" color="#fff"></u-icon>
            <text>VIP</text>
          </view>
        </view>
        <view class="user-info">
          <view class="name-row">
            <text class="nickname" v-if="isLogin">{{ userInfo.nickname }}</text>
            <view class="login-btn" v-else @click="handleLogin">登录 / 注册</view>
            <!-- <text class="user-id" v-if="isLogin">ID: {{ userInfo.id }}</text> -->
          </view>
          <view class="user-tags" v-if="isLogin">
            <text class="tag">{{ getGenderText(userInfo.gender) }}</text>
            <text class="tag">{{ formatPhone(userInfo.phone) }}</text>
          </view>
        </view>
      </view>

      <!-- 用户资产信息 -->
      <view class="assets-overview">
        <view class="asset-item" v-for="(item, index) in assetMenu" :key="index" @click="navigateTo(item.url)">
          <text class="asset-value">{{ item.number }}</text>
          <text class="asset-label">{{ item.title }}</text>
        </view>
      </view>
    </view>

    <!-- 订单卡片 -->
    <view class="card order-card">
      <view class="card-header">
        <text class="title">我的订单</text>
        <view class="more" @click="handleOrderClick">
          <text>查看全部</text>
          <u-icon name="arrow-right" size="20" color="#999"></u-icon>
        </view>
      </view>
      <view class="order-grid">
        <view class="grid-item" v-for="(item, index) in orderMenu" :key="index" @click="navigateToOrder(item.url)">
          <view class="icon-wrapper">
            <u-icon :name="item.icon" size="36" color="#00b578"></u-icon>
            <view class="badge" v-if="item.badge">{{ item.badge }}</view>
          </view>
          <text>{{ item.title }}</text>
        </view>
      </view>
    </view>

    <!-- 工具卡片 -->
    <view class="card tools-card">
      <view class="card-header">
        <text class="title">常用工具</text>
      </view>
      <view class="tools-grid">
        <view 
          class="tool-item" 
          v-for="(item, index) in toolsMenu" 
          :key="index"
          @click="navigateTo(item.url)"
        >
          <view class="tool-icon">
            <u-icon :name="item.icon" size="36" :color="item.color || '#07c160'"></u-icon>
          </view>
          <text>{{ item.title }}</text>
        </view>
      </view>
    </view>

    <!-- 猜你喜欢 -->
    <view class="recommend-section">
      <view class="section-header">
        <text class="title">猜你喜欢</text>
      </view>
      <view class="recommend-grid">
        <view 
          class="recommend-item" 
          v-for="(item, index) in recommendList" 
          :key="index"
          @click="navigateToProduct(item.id)"
        >
          <image :src="item.imageUrl" mode="aspectFill" class="product-image"></image>
          <view class="product-info">
            <view class="product-title">
              <text class="origin">[{{ item.origin }}]</text>
              {{ item.name }}
            </view>
            <text class="product-desc">{{ item.description }}</text>
            <view class="product-footer">
              <view class="price-section">
                <text class="price">¥{{ item.discountPrice || item.price }}</text>
                <text class="original-price" v-if="item.discountPrice">¥{{ item.price }}</text>
              </view>
              <text class="sales">已售{{ formatSales(item.sales) }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useAuthStore } from '../../store/auth'
import { useProductStore } from '../../store/productStore'
import { usePointsStore } from '../../store/pointsStore'
import { onShow } from '@dcloudio/uni-app'

const authStore = useAuthStore()
const productStore = useProductStore()
const pointsStore = usePointsStore()

const isLogin = computed(() => authStore.isLoggedIn)
const userInfo = computed(() => authStore.userInfo)
const recommendList = computed(() => productStore.recommendProducts)

// 格式化手机号
const formatPhone = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 格式化销量
const formatSales = (sales) => {
  if (sales >= 10000) {
    return (sales / 10000).toFixed(1) + '万'
  }
  return sales
}

const getGenderText = (gender) => {
  const genderMap = {
    0: '未知',
    1: '男',
    2: '女',
  }
  return genderMap[gender] || '未知'
}

// 订单菜单配置
const orderMenu = ref([
  { icon: 'rmb-circle', title: '待付款', url: '/pages/order/order?status=0', status: 0 },
  { icon: 'gift', title: '待发货', url: '/pages/order/order?status=1', status: 1 },
  { icon: 'car', title: '待收货', url: '/pages/order/order?status=2', status: 2 },
  { icon: 'star', title: '待评价', url: '/pages/order/order?status=5', status: 5 }
])

// 工具菜单配置
const toolsMenu = ref([
  { icon: 'server-man', title: '客服服务', url: '/pages/message/components/chat', color: '#e74c3c' },
  { icon: 'map', title: '地址管理', url: '/pages/user/components/address', color: '#3498db' },
  // { icon: 'star', title: '我的收藏', url: '/pages/user/components/favorites', color: '#f39c12' },
  { icon: 'coupon', title: '优惠券', url: '/pages/user/components/coupons', color: '#9b59b6' },
  // { icon: 'calendar', title: '签到', url: '/pages/user/components/checkin', color: '#2ecc71' },
  { icon: 'shopping-cart', title: '购物车', url: '/pages/car/index', color: '#1abc9c' },
  // { icon: 'chat', title: '问答社区', url: '/pages/user/components/community', color: '#e67e22' },
  // { icon: 'file-text', title: '意见反馈', url: '/pages/user/components/feedback', color: '#34495e' }
])

// 资产菜单
const assetMenu = computed(() => [
  {
    number: pointsStore.getPointsOverview.totalPoints || '0',
    title: '积分',
    url: '/pages/user/components/points'
  },
  {
    number: (pointsStore.getPointsOverview.totalPoints / 100 || 0).toFixed(2),
    title: '红包',
    url: '/pages/user/components/redpacket'
  },
  {
    number: '3',
    title: '优惠券',
    url: '/pages/user/components/coupons'
  },
  {
    number: '0',
    title: '礼品卡',
    url: '/pages/user/components/giftcards'
  }
])

// 页面方法
const navigateTo = (url) => {
  // 检查是否为tabBar页面
  const tabBarPages = [
    '/pages/home/index',
    '/pages/classes/index',
    '/pages/message/message',
    '/pages/car/index',
    '/pages/user/index'
  ];
  
  if (tabBarPages.some(tabUrl => url.startsWith(tabUrl))) {
    uni.switchTab({ url });
  } else {
    uni.navigateTo({ url });
  }
}

const navigateToProduct = async (id) => {
  try {
    await productStore.loadProductDetail(id)
    uni.navigateTo({
      url: `/pages/classes/components/product-detail?detailId=${id}`
    })
  } catch (error) {
    uni.showToast({
      title: '加载商品详情失败',
      icon: 'none'
    })
  }
}

const handleLogin = () => {
  uni.navigateTo({
    url: '/pages/login/login'
  })
}

const handleOrderClick = () => {
  uni.navigateTo({
    url: '/pages/order/order'
  })
}

// 处理设置
const handleSettings = () => {
  uni.navigateTo({
    url: '/pages/user/components/profile'
  })
}

// 订单专用跳转方法
const navigateToOrder = (url) => {
  uni.navigateTo({ url });
}

onMounted(async () => {
  await authStore.initFromStorage()
  await Promise.all([
    loadRecommendData(),
    pointsStore.loadPointsOverview()
  ])
})

// 监听userInfo变化
watch(() => authStore.userInfo, (newVal) => {
}, { deep: true })

onShow(async () => {
  authStore.initFromStorage()
  await Promise.all([
    loadRecommendData(),
    pointsStore.loadPointsOverview()
  ])
})

const loadRecommendData = async () => {
  try {
    await productStore.loadRecommendProducts(10)
  } catch (error) {
    console.error('加载推荐商品失败:', error)
  }
}
</script>

<style lang="scss" scoped>
.user-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: env(safe-area-inset-bottom);
}

.profile-section {
  background: linear-gradient(135deg, #00b578, #91ccf3);
  padding: 40rpx 30rpx;
  color: #ffffff;
  position: relative;
  
  .header-actions {
    position: absolute;
    top: 20rpx;
    right: 30rpx;
    display: flex;
    gap: 30rpx;

    .action-btn {
      width: 80rpx;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
      backdrop-filter: blur(10px);
      
      &:active {
        transform: scale(0.95);
        opacity: 0.8;
      }
    }
  }
  
  .profile-header {
    display: flex;
    align-items: center;
    margin-bottom: 40rpx;
    
    .avatar-wrapper {
      position: relative;
      margin-right: 30rpx;
      
      .avatar-placeholder {
        width: 120rpx;
        height: 120rpx;
        background: rgba(255,255,255,0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 40rpx;
        color: #ffffff;
        border-radius: 50%;
      }
      
      .vip-badge {
        position: absolute;
        bottom: 0;
        right: 0;
        background: linear-gradient(135deg, #ffd700, #ffaa00);
        border-radius: 16rpx;
        padding: 2rpx 10rpx;
        display: flex;
        align-items: center;
        border: 2rpx solid #ffffff;
        
        text {
          font-size: 18rpx;
          margin-left: 2rpx;
        }
      }
    }
    
    .user-info {
      flex: 1;
      
      .name-row {
        display: flex;
        align-items: center;
        margin-bottom: 12rpx;
        
        .nickname {
          font-size: 36rpx;
          font-weight: 600;
          margin-right: 16rpx;
        }
        
        .login-btn {
          font-size: 28rpx;
          background: rgba(255,255,255,0.2);
          padding: 8rpx 24rpx;
          border-radius: 24rpx;
          
          &:active {
            opacity: 0.8;
          }
        }
        
        .user-id {
          font-size: 22rpx;
          opacity: 0.8;
          margin-left: auto;
        }
      }
      
      .user-tags {
        display: flex;
        gap: 16rpx;
        
        .tag {
          font-size: 24rpx;
          background: rgba(255,255,255,0.2);
          padding: 4rpx 16rpx;
          border-radius: 20rpx;
        }
      }
    }
  }
  
  .assets-overview {
    display: flex;
    background: rgba(255,255,255,0.1);
    border-radius: 16rpx;
    padding: 20rpx 0;
    
    .asset-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;
      
      &:not(:last-child)::after {
        content: '';
        position: absolute;
        right: 0;
        top: 20%;
        height: 60%;
        width: 1px;
        background: rgba(255,255,255,0.2);
      }
      
      .asset-value {
        font-size: 36rpx;
        font-weight: 600;
        margin-bottom: 8rpx;
        color: #ffffff;
        text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.1);
      }
      
      .asset-label {
        font-size: 24rpx;
        opacity: 0.9;
        color: rgba(255,255,255,0.9);
      }
    }
  }
}

.card {
  background: #ffffff;
  border-radius: 16rpx;
  margin: 20rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333333;
    }
    
    .more {
      display: flex;
      align-items: center;
      color: #999999;
      font-size: 26rpx;
      
      text {
        margin-right: 8rpx;
      }
    }
  }
}

.order-grid {
  display: flex;
  justify-content: space-around;
  
  .grid-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .icon-wrapper {
      position: relative;
      margin-bottom: 12rpx;
      
      .badge {
        position: absolute;
        top: -8rpx;
        right: -8rpx;
        background: #ff4d4f;
        color: #ffffff;
        font-size: 18rpx;
        min-width: 28rpx;
        height: 28rpx;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 6rpx;
      }
    }
    
    text {
      font-size: 24rpx;
      color: #333333;
    }
  }
}

.tools-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24rpx;
  
  .tool-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .tool-icon {
      margin-bottom: 8rpx;
      transition: transform 0.2s;
      
      &:active {
        transform: scale(0.9);
      }
    }
    
    text {
      font-size: 24rpx;
      color: #333333;
    }
  }
}

.recommend-section {
  margin: 20rpx;
  
  .section-header {
    margin-bottom: 20rpx;
    
    .title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333333;
    }
  }
  
  .recommend-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
    
    .recommend-item {
      background: #ffffff;
      border-radius: 12rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);
      
      .product-image {
        width: 100%;
        height: 320rpx;
        background: #f8f8f8;
      }
      
      .product-info {
        padding: 16rpx;
        
        .product-title {
          font-size: 28rpx;
          color: #333333;
          line-height: 1.4;
          margin-bottom: 8rpx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
          
          .origin {
            color: #3498db;
            margin-right: 8rpx;
          }
        }
        
        .product-desc {
          font-size: 24rpx;
          color: #999999;
          line-height: 1.4;
          margin-bottom: 16rpx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          overflow: hidden;
        }
        
        .product-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .price-section {
            display: flex;
            align-items: baseline;
            gap: 8rpx;
            
            .price {
              font-size: 32rpx;
              font-weight: 600;
              color:#ff8800;
            }
            
            .original-price {
              font-size: 24rpx;
              color: #999999;
              text-decoration: line-through;
            }
          }
          
          .sales {
            font-size: 22rpx;
            color: #999999;
          }
        }
      }
    }
  }
}
</style>
